package cn.iocoder.yudao.module.scrm.service.business;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.dict.core.util.DictFrameworkUtils;
import cn.iocoder.yudao.framework.excel.core.strategy.DictTenantContext;
import cn.iocoder.yudao.module.scrm.controller.admin.business.vo.business.BusinessDetailVO;
import cn.iocoder.yudao.module.scrm.controller.admin.business.vo.business.BusinessPageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.business.vo.business.BusinessRespVO;
import cn.iocoder.yudao.module.scrm.controller.admin.business.vo.business.BusinessSaveReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.business.BusinessDO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.scrm.dal.mysql.business.ScrmBusinessMapper;
import cn.iocoder.yudao.module.scrm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.scrm.service.customer.CustomerService;
import cn.iocoder.yudao.module.scrm.util.CheckNoGeneratorUtil;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.scrm.enums.DictTypeConstants.*;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.BUSINESS_NOT_EXISTS;

/**
 * 商机 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class BusinessServiceImpl implements BusinessService {

    @Resource
    private ScrmBusinessMapper businessMapper;

    @Resource
    private CustomerService customerService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private DeptApi deptApi;

    @Resource
    private CheckNoGeneratorUtil checkNoGeneratorUtil;

    @Override
    public Integer createBusiness(BusinessSaveReqVO createReqVO) {
        // 插入
        BusinessDO business = BeanUtils.toBean(createReqVO, BusinessDO.class);
        business.setSystemNumber(checkNoGeneratorUtil.generateUniqueCheckNo(CrmBizTypeEnum.CRM_BUSINESS.getType()));
        businessMapper.insert(business);
        // 返回
        return business.getId();
    }

    @Override
    public void updateBusiness(BusinessSaveReqVO updateReqVO) {
        // 校验存在
        validateBusinessExists(updateReqVO.getId());
        //进行比较如果归属人更换了，重新设置前归属人
        BusinessDO business = this.getBusiness(updateReqVO.getId());
        //当传入的归属人与之前的不一样设置前归属人
        if (business.getVestingOfficer()!=null && !business.getVestingOfficer().equals(updateReqVO.getVestingOfficer())){
            updateReqVO.setOldOwnerUserId(business.getVestingOfficer());
        }else{
            updateReqVO.setVestingOfficer(updateReqVO.getVestingOfficer());
        }
        // 更新
        BusinessDO updateObj = BeanUtils.toBean(updateReqVO, BusinessDO.class);
        businessMapper.updateById(updateObj);
    }

    @Override
    public void deleteBusiness(Integer id) {
        // 校验存在
        validateBusinessExists(id);
        // 删除
        businessMapper.deleteById(id);
    }

    private void validateBusinessExists(Integer id) {
        if (businessMapper.selectById(id) == null) {
            throw exception(BUSINESS_NOT_EXISTS);
        }
    }

    @Override
    public BusinessDO getBusiness(Integer id) {
        return businessMapper.selectById(id);
    }



    @Override
    public BusinessDetailVO getBusinessDetail(Integer id, String tenantId) {
        BusinessDO businessDO = businessMapper.selectById(id);
        BusinessDetailVO detailVO = BeanUtils.toBean(businessDO, BusinessDetailVO.class);

        // 获取当前归属人部门信息
        setDeptInfo(detailVO, detailVO.getVestingOfficer(), tenantId, true);

        // 获取前归属人部门用户信息
        setDeptInfo(detailVO, businessDO.getOldOwnerUserId(), tenantId, false);

        // 根据客户id查询关联客户姓名和主要联系人
        if (businessDO.getCustomerId() != null) {
            CustomerDO customer = customerService.getCustomer(Long.valueOf(businessDO.getCustomerId()));
            if (customer != null) {
                detailVO.setCustomerName(Optional.ofNullable(customer.getName()).orElse(""));
                detailVO.setCustomerEnterprise(Optional.ofNullable(customer.getEnterprise()).orElse(""));
                detailVO.setPhone(Optional.ofNullable(customer.getPhone()).orElse(""));
            }
        }

        // 返回创建人姓名
        Optional.ofNullable(businessDO.getCreator())
                .map(creator -> adminUserApi.getUserNotCheckDataPermission(Long.valueOf(creator)).getCheckedData())
                .ifPresent(userRespDTO -> detailVO.setCreator(userRespDTO.getNickname()));

        return detailVO;
    }

    private void setDeptInfo(BusinessDetailVO detailVO, String userId, String tenantId, boolean isCurrent) {
        if (userId != null && !userId.isEmpty()) {
            AdminUserRespDTO userRespDTO = adminUserApi.getLeaderByWxIdNotCheckDataPermission(userId, tenantId).getCheckedData();
            if (userRespDTO != null) {
                DeptRespDTO deptRespDTO = deptApi.getDeptNotCheckDataPermission(userRespDTO.getDeptId()).getCheckedData();
                if (isCurrent) {//当前的归属人员部门信息
                    detailVO.setVestingOfficerName(userRespDTO.getNickname());
                    detailVO.setVestingOfficerDept(Optional.ofNullable(deptRespDTO).map(DeptRespDTO::getName).orElse(""));
                } else {//之前的用户-部门信息
                    detailVO.setOldOwnerUserIdDept(Optional.ofNullable(deptRespDTO).map(DeptRespDTO::getName).orElse(""));
                    detailVO.setOldOwnerUserIdName(Optional.of(userRespDTO).map(AdminUserRespDTO::getNickname).orElse(""));
                }
            }
        }
    }



    @Override
    public PageResult<BusinessRespVO> getBusinessPage(BusinessPageReqVO pageReqVO,Integer tenantId) {
        PageResult<BusinessRespVO> businessDoPageResult = businessMapper.selectPages(pageReqVO);
        PageResult<BusinessRespVO> respVo = BeanUtils.toBean(businessDoPageResult, BusinessRespVO.class);

        DictTenantContext tenantContext = new DictTenantContext(tenantId);

        //根据值不为空进行缓存中的字典查询-改为用注解的方式转换
        List<BusinessRespVO> businessDOList = respVo.getList();
        businessDOList.forEach(businessDO -> {
            Optional<String> salesStageOptional = Optional.ofNullable(businessDO.getSalesStage());
            salesStageOptional.ifPresent(salesStage -> businessDO.setSalesStage(tenantContext.getDictDataLabel(SCRM_SALES_STAGE, salesStage)));

            Optional<String> businessTypeOptional = Optional.ofNullable(businessDO.getBusinessType());
            businessTypeOptional.ifPresent(businessType -> businessDO.setBusinessType(tenantContext.getDictDataLabel(SCRM_BUSINESS_TYPE, businessType)));

            Optional<String> tpbOptional = Optional.ofNullable(businessDO.getTransactionProbability());
            tpbOptional.ifPresent(tpb -> businessDO.setTransactionProbability(DictFrameworkUtils.getDictDataLabel(SCRM_TRANSACTION_PROBABILITY, tpb)));

            Optional<String> sourceOptional = Optional.ofNullable(businessDO.getBusinessSource());
            sourceOptional.ifPresent(source -> businessDO.setBusinessSource(tenantContext.getDictDataLabel(SCRM_BUSINESS_SOURCE, source)));

            Optional<String> signCondition = Optional.ofNullable(businessDO.getSignCondition());
            signCondition.ifPresent(source -> businessDO.setSignCondition(tenantContext.getDictDataLabel(SCRM_SIGN_CONDITION, source)));


        });

        return respVo;
    }

    @Override
    public PageResult<BusinessRespVO> getBusinessPageExport(BusinessPageReqVO pageReqVO) {
       return businessMapper.selectPages(pageReqVO);
    }

}